import os,base64
from time import sleep
from support.stream.bilibilistreaming import BiliStreaming
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
 
class Bilibili:
    def __init__(self, *, hubaddr, hubport=4444):
        options = Options()
        options.add_argument("--start-maximized")
        self.driver = webdriver.Remote('http://{}:{}/wd/hub'.format(hubaddr, hubport), options=options)

    def close(self):
        self.driver.quit()

    def login(self, url, expected_url):
        self.driver.get(url)
        while(self.driver.current_url != expected_url):
            qrlist = self.driver.find_elements(By.XPATH, '//div[@class="login-scan__qrcode"]//img')
            if(len(qrlist) == 1):
                print("Waiting for scan to login")
                self.saveImage(qrlist[0])
                os.system("convert login.png login.jpg")
                os.system("jp2a login.jpg")
                #os.system("rm login.jpg login.png")
                sleep(60)
            if(self.driver.current_url == expected_url):
                break
            self.driver.get(url)
    
    def saveImage(self, element):
        try:
            base64_string = element.get_attribute("src")
            img_data = base64.b64decode(base64_string)
            img_bytes = BytesIO(img_data)
            image = Image.open(img_bytes)
            image.save("login.png", "png")
        except Exception:
            element.screenshot("login.png")
    
    def getCookie(self):
        cookies = self.driver.get_cookies()
        info = ""
        for cookie in cookies:
            info += "{}={};".format(cookie["name"], cookie["value"])
        return info



if __name__ == "__main__":
    browser = Bilibili(hubaddr="selenium-hub")
    try:
        browser.login("https://passport.bilibili.com/login", "https://www.bilibili.com/")
        cookie = browser.getCookie()
    finally:
        browser.close()
    streaming = BiliStreaming(os.path.join(os.path.dirname(__file__), "support", "tools", "bilibilistreaming"))
    streaming.updateCookie(cookie)
    ret = ""
    while(streaming.untilRemoteServerOpend()):
        try:
            ret = streaming.start()
        except:
            print("Push Err", ret)
